package com.powerunion.datacollection.service;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.powerunion.datacollection.common.Constants;
import com.powerunion.datacollection.common.SystemException;
import com.powerunion.datacollection.dao.DaoException;
import com.powerunion.datacollection.dao.DaoFactory;
import com.powerunion.datacollection.dao.MaintblDataDao;
import com.powerunion.datacollection.model.ApproveWorkItem;
import com.powerunion.datacollection.model.MaintblData;
import com.powerunion.datacollection.model.SubmissionWorkItem;
import com.powerunion.datacollection.model.jsonObject.DBTableField;
import com.powerunion.util.log.LogHelper;

public class MaintblDataManager {
	private static Logger logger = LogHelper.getInstance().getLogger(
			MaintblDataManager.class);
	private MaintblDataDao dao = null;

	public MaintblDataManager() {
		super();
		this.dao = (MaintblDataDao) DaoFactory.getInstance().getDao(
				MaintblDataDao.class);
	}

	public boolean save(MaintblData data, String formValues) throws Exception {
		// 参数为空
		if (StringUtils.isEmpty(formValues)) {
			String[] args = { "formValues" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter formValues NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		return this.dao.save(data, formValues);

	}

	public JSONObject getMaintblDataInfo(MaintblData data) throws DaoException {
		// 参数为空
		if (data == null) {
			String[] args = { "data" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter data NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		JSONObject jsonObject = this.dao.getMaintblDataInfo(data);
		return jsonObject;
	}

	// public String getMaintblDataInfo4SubFormMaintTbl(MaintblData data)
	// throws DaoException {
	// // 参数为空
	// if (data == null) {
	// String[] args = { "data" };
	// // 打印错误日志
	// StringBuffer msglog = new StringBuffer(
	// "empty invoke parameter data NULL ");
	// logger.error(msglog.toString());
	// throw new SystemException("error.common.parameter.empty", args);
	// }
	//
	// JSONObject jsonObject = this.dao
	// .getMaintblDataInfo4SubFormMaintTbl(data);
	// String info = "{success:true,data:[" + jsonObject + "]}";
	//
	// return info;
	// }

	public String getAllMaintblDatasByAct(String procId, String actId,
			int currentOrparrent) throws Exception {
		// 参数为空
		if (StringUtils.isEmpty(procId)) {
			String[] args = { "procId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter procId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		// 参数为空
		if (StringUtils.isEmpty(actId)) {
			String[] args = { "actId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter data NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		ApproveWorkItemManager awm = new ApproveWorkItemManager();
		ApproveWorkItem awi = awm.getByKey(actId);
		SubmissionWorkItemManager swm = new SubmissionWorkItemManager();
		List SubmissionWorkItems = new ArrayList();
		if (currentOrparrent == Constants.DATACOLLECTVIEW_REQUEST_TYPE_SUBMIDATA) {// 请求的是当前上报的任务数据
			// 得到当前上报的步骤类型
			int preActType = awi.getPreActType();
			String preActId = awi.getPreActId();

			// 当前上报的是采集步骤
			if (preActType == Constants.COLLECTION_STEP_TYPE) {
				SubmissionWorkItems = swm.getAllSubWorksByAct(procId, preActId,
						1);
			} else if (currentOrparrent == Constants.APPROVE_STEP_TYPE) {
				SubmissionWorkItems = swm.getAllSubWorksByAct(procId, preActId,
						2);
			}

		} else if (currentOrparrent == Constants.DATACOLLECTVIEW_REQUEST_TYPE_COLLECT) {// 请求的是汇总所有上报数据
			SubmissionWorkItems = swm.getAllSubWorksByAct(procId, actId, 2);
		}
		if (SubmissionWorkItems.size() < 1) {
			return "{results:''}";
		} else {
			SubmissionWorkItem swi = (SubmissionWorkItem) SubmissionWorkItems
					.get(0);
			List fields = this.dao.getMaintblFields(swi.getFormId());
			String result = "";
			if (fields.isEmpty()) {
				return result = "{results:''}";
			}

			List maintblDatas = this.dao
					.getAllMaintblDataByAct(SubmissionWorkItems);

			List allMaintblDatas = new ArrayList();
			// 重组数据
			for (int i = 0; i < fields.size(); i++) {
				DBTableField df = (DBTableField) fields.get(i);
				JSONObject record = new JSONObject();
				// 主表字段名为第一列
				record.put("column0", df.getFieldLabel());
				// 遍历主表数据 依次取出同个主表字段对应的值
				for (int j = 0; j < maintblDatas.size(); j++) {
					JSONObject jo = (JSONObject) maintblDatas.get(j);
					int index = j + 1;
					record.put("column" + index, jo.get(df.getFieldName()));
				}
				allMaintblDatas.add(record);
			}

			JSONArray jsonArr = JSONArray.fromObject(allMaintblDatas);
			result = "{results:" + jsonArr + "}";
			return result;
		}

	}

	public List getMaintblFields(String formId) throws DaoException {
		// 参数为空
		if (StringUtils.isEmpty(formId)) {
			String[] args = { "formId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter formId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		return this.dao.getMaintblFields(formId);
	}

	public boolean deleteFormData(MaintblData data, Connection conn, String sql)
			throws Exception {
		// 参数为空
		if (data == null) {
			String[] args = { "data" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter data NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		// 参数为空
		if (conn == null) {
			String[] args = { "conn" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter conn NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		// 参数为空
		if (StringUtils.isEmpty(sql)) {
			String[] args = { "sql" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter sql NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		return this.dao.deleteFormData(data, conn, sql);
	}

	public boolean deleteMaintblData(MaintblData data, Connection conn)
			throws DaoException {
		if (data == null) {
			String[] args = { "data" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter data NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		// 参数为空
		if (conn == null) {
			String[] args = { "conn" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter conn NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		return this.dao.deleteMaintblData(data, conn);
	}

	public boolean saveMaintblData(MaintblData data) throws Exception {
		if (data == null) {
			String[] args = { "data" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter data NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		return this.dao.saveMaintblData(data);
	}

	public String getMaintblDataByKey(MaintblData data, Connection conn)
			throws Exception {
		if (data == null) {
			String[] args = { "data" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter data NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		if (conn == null) {
			String[] args = { "conn" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter conn NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		return this.dao.getMaintblDataByKey(data, conn);
	}

	public String getMaintblDataByKey4Init(MaintblData data, Connection conn)
			throws Exception {
		if (data == null) {
			String[] args = { "data" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter data NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		if (conn == null) {
			String[] args = { "conn" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter conn NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		return this.dao.getMaintblDataByKey4Init(data, conn);
	}

	public List getAllMaintblDataByAct4subTbl(List submissionWorks)
	throws Exception{
		return this.dao.getAllMaintblDataByAct4subTbl(submissionWorks);
	}
}
